﻿/*******************************************************************
 *  Copyright(c) 2018-2018 A single spark
 *  All rights reserved.
 *
 *  文件名称:   yuvvideolistwidget.cpp
 *  简要描述:   用于播放列表的文件名和文件路径显示
 *
 *  创建日期:   2018.03.10
 *  作者:      Enum.Bai
 *  邮箱:      1040433764@qq.com
 *  说明:
 *
 *  修改日期:
 *  作者:
 *  邮箱:
 *  说明:
 ******************************************************************/

#include "yuvvideolistwidget.h"
#include "yuvmsgnotifysington.h"
#include "define.h"

#include <QTreeWidget>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>

#include <QSettings>
#include <QFileInfo>
#include <QAction>
#include <QMenu>

#include <QDebug>

YUVVideoListWidget::YUVVideoListWidget(QWidget *parent)
    : YUVWidget(parent),
      m_pPlayListWidgt(Q_NULLPTR)
{
    setObjectName("YUVVideoListWidget");
    setFixedSize(YUVTool::VideoListFixedWidth, YUVTool::VideoListFixedHeight);

    m_pPlayListWidgt = new QTreeWidget(this);
    m_pPlayListWidgt->setFixedSize(YUVTool::VideoListFixedWidth, YUVTool::VideoListFixedHeight);
    m_pPlayListWidgt->setHeaderLabels(QStringList() << tr("video play list"));

    m_pPlayListWidgt->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(YUVMsgNotifySington::instance(), &YUVMsgNotifySington::playListUpdate,
            this, &YUVVideoListWidget::updatePlayList);

    connect(m_pPlayListWidgt, &QTreeWidget::itemDoubleClicked, this, &YUVVideoListWidget::playListClicked);
    connect(m_pPlayListWidgt, &QTreeWidget::customContextMenuRequested, this, &YUVVideoListWidget::showTreeRightMenu);
    connect(m_pPlayListWidgt, &QTreeWidget::currentItemChanged, this, &YUVVideoListWidget::onCurrentItemChanged);

    setAcceptDrops(true);
    setStyleSheet(QLatin1String(Utils::FileReader::fetchQrc(":/resource/zh_ch/qss/videoList.css")));

    m_pDelAction = new QAction(tr("del"), this);
    connect(m_pDelAction, &QAction::triggered, this, &YUVVideoListWidget::removeItem);

    m_pMenu = new QMenu(this);
    m_pMenu->addAction(m_pDelAction);

    initPlayList();
}

YUVVideoListWidget::~YUVVideoListWidget()
{

}

//当用户拖动文件到窗口部件上时候，就会触发dragEnterEvent事件
void YUVVideoListWidget::dragEnterEvent(QDragEnterEvent *event)
{
    //如果为文件，则支持拖放
    if (event->mimeData()->hasFormat("text/uri-list"))
    {
        event->acceptProposedAction();
    }
}

//当用户放下这个文件后，就会触发dropEvent事件
void YUVVideoListWidget::dropEvent(QDropEvent *event)
{
    //注意：这里如果有多文件存在，意思是用户一下子拖动了多个文件，而不是拖动一个目录
    //如果想读取整个目录，则在不同的操作平台下，自己编写函数实现读取整个目录文件名
    QList<QUrl> urls = event->mimeData()->urls();
    if(urls.isEmpty())
    {
        return;
    }

    //往文本框中追加文件名
    foreach(QUrl url, urls)
    {
        QString filepath = url.toLocalFile();

        int first = filepath.lastIndexOf ("/"); //从后面查找"/"位置
        QString fileName = filepath.mid(first+1);
        qDebug() << fileName;

        int second = fileName.lastIndexOf(".");//查找后缀名位置
        QString fileNameWithoutDot = fileName.left(second);//选中.左边的字符
        qDebug() << fileNameWithoutDot;

        QTreeWidgetItem *pItem = new QTreeWidgetItem;
        pItem->setText(0, fileNameWithoutDot);
        pItem->setToolTip(0, filepath);
        m_pPlayListWidgt->insertTopLevelItem(0, pItem);

        savePlayList(filepath);
        //qDebug() << "---------" << filepath;
    }
}

void YUVVideoListWidget::updatePlayList(QString &filePath)
{
    int first = filePath.lastIndexOf ("/"); //从后面查找"/"位置
    QString fileName = filePath.mid(first+1);
    //qDebug() << fileName;

    int second = fileName.lastIndexOf(".");//查找后缀名位置
    QString fileNameWithoutDot = fileName.left(second);//选中.左边的字符
    //qDebug() << fileNameWithoutDot;

    QTreeWidgetItem *pItem = new QTreeWidgetItem;
    pItem->setText(0, fileNameWithoutDot);
    pItem->setToolTip(0, filePath);
    m_pPlayListWidgt->insertTopLevelItem(0, pItem);

    savePlayList(filePath);
}

void YUVVideoListWidget::playListClicked(QTreeWidgetItem *item, int column)
{
    if (Q_NULLPTR == item)
    {
        return;
    }

    YUVMsgNotifySington::instance()->notifyPlayInit(item->toolTip(column));
}

void YUVVideoListWidget::showTreeRightMenu(QPoint pos)
{
    Q_UNUSED(pos);

    QTreeWidgetItem *pItem = m_pPlayListWidgt->itemAt(pos);
    if (Q_NULLPTR != pItem) {
        m_pMenu->move(m_pPlayListWidgt->cursor().pos());
        m_pMenu->exec();
    } else {
        m_pPlayListWidgt->setCurrentItem(Q_NULLPTR);
    }
}

void YUVVideoListWidget::removeItem()
{
    QTreeWidgetItem *pItem = m_pPlayListWidgt->currentItem();
    if (Q_NULLPTR != pItem)
    {
        removePlayList(pItem->text(0));
        m_pPlayListWidgt->takeTopLevelItem(m_pPlayListWidgt->indexOfTopLevelItem(pItem));
    }
}

void YUVVideoListWidget::onCurrentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    Q_UNUSED(previous);

    if (Q_NULLPTR != current)
    {
        emit currentNameChanged(current->toolTip(0));
    }
}

void YUVVideoListWidget::initPlayList()
{
    QSettings settings("YUV", "YUVToolChina");

    QStringList baseNameList = settings.allKeys();

    foreach (QString baseName, baseNameList)
    {
        QString filePath = settings.value(baseName).toString();
        QFileInfo fileInfo(filePath);

        if (fileInfo.exists())
        {
            QTreeWidgetItem *pItem = new QTreeWidgetItem;
            pItem->setText(0, baseName);
            pItem->setToolTip(0, settings.value(baseName).toString());
            m_pPlayListWidgt->insertTopLevelItem(0, pItem);
        }
        else
        {
            settings.remove(baseName);
        }
    }
}

void YUVVideoListWidget::savePlayList(const QString &filePath)
{
    QSettings settings("YUV", "YUVToolChina");

    QFileInfo fileInfo(filePath);
    QString baseName = fileInfo.baseName();

    QStringList nameList = settings.allKeys();

    if (!nameList.contains(fileInfo.fileName()))
    {
        settings.setValue(baseName, filePath);
    }
}

void YUVVideoListWidget::removePlayList(const QString &baseName)
{
    QSettings settings("YUV", "YUVToolChina");

    settings.remove(baseName);
}
